/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.buffer;

import com.aduib.boot.common.util.ExceptionUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @description: BufferInputStream
 * @author: zzh
 * @date: 2021/12/13 15:51
 */
public class BufferedInputStream extends InputStream {

  private Buffer buf;

  private int mark = -1;

  private boolean isClosed = false;

  public BufferedInputStream(Buffer buf) {
    this.buf = buf;
  }

  @Override
  public int read() throws IOException {
    ExceptionUtils.throwStreamAlreadyClosedException(isClosed);
    if (buf.readableBytes() > 0) return buf.readByte() & 0xff;
    return -1;
  }

  @Override
  public int read(byte[] b) throws IOException {
    ExceptionUtils.throwStreamAlreadyClosedException(isClosed);
    return buf.read(b);
  }

  @Override
  public int read(byte[] b, int off, int len) throws IOException {
    ExceptionUtils.throwStreamAlreadyClosedException(isClosed);
    return buf.read(b, off, len);
  }

  public byte[] readAllBytes() throws IOException {
    ExceptionUtils.throwStreamAlreadyClosedException(isClosed);
    return buf.readByteArray();
  }

  @Override
  public long skip(long n) throws IOException {
    ExceptionUtils.throwStreamAlreadyClosedException(isClosed);
    buf.skip(n);
    return n;
  }

  @Override
  public int available() throws IOException {
    return (int) Math.min(buf.readableBytes(), Integer.MAX_VALUE);
  }

  @Override
  public synchronized void mark(int readlimit) {
    mark = readlimit;
    buf.markReaderIndex();
  }

  @Override
  public synchronized void reset() throws IOException {
    buf.resetReaderIndex();
  }

  @Override
  public boolean markSupported() {
    return true;
  }

  @Override
  public void close() throws IOException {
    BufferUtils.freeBuffer(buf);
    this.isClosed = true;
  }

  public long transferTo(OutputStream out) throws IOException {
    ExceptionUtils.throwStreamAlreadyClosedException(isClosed);
    int readableBytes = buf.readableBytes();
    out.write(buf.readByteArray());
    return readableBytes;
  }
}
